import * as winston from 'winston';
import * as DailyRotateFile from 'winston-daily-rotate-file';
import { Injectable } from '@nestjs/common';

const logFormat = winston.format.printf(({ level, message, timestamp }) => {
  return `${timestamp} [${level.toUpperCase()}]: ${message}`;
});

@Injectable()
export class LoggerService {
  private logger: winston.Logger;

  constructor() {
    this.logger = winston.createLogger({
      format: winston.format.combine(winston.format.timestamp(), logFormat),
      transports: [
        new winston.transports.Console(),
        // new winston.transports.File({
        //   filename: 'logs/error.log',
        //   level: 'error',
        // }),
        // new winston.transports.File({ filename: 'logs/combined.log' }),
        // 按日期分隔日志文件
        new DailyRotateFile({
          // level: 'info',
          dirname: 'logs', // 存放日志的目录
          filename: 'combined-%DATE%.log',
          datePattern: 'YYYY-MM-DD',
          zippedArchive: true,
          maxFiles: '6M', // 保留最近 6 个月的日志
        }),
        new DailyRotateFile({
          level: 'error',
          dirname: 'logs', // 存放日志的目录
          filename: 'error-%DATE%.log',
          datePattern: 'YYYY-MM-DD',
          zippedArchive: true,
          maxFiles: '6M', // 保留最近 6 个月的日志
        }),
      ],
    });
  }

  log(message: string) {
    this.logger.log('info', message);
  }

  error(message: string, trace: string) {
    this.logger.error(`${message} ${trace}`);
  }

  warn(message: string) {
    this.logger.warn(message);
  }

  debug(message: string) {
    this.logger.debug(message);
  }
}
